<template>
  <div class="page_content daraBoardStreetAnalysis_content">
    <div class="header_box p-12 bold flex flex-ac flex-jsb">
      <div class="title flex flex-ac">
        <div class="mr-30">厢牌列表 </div>
      </div>
      <div class="flex flex-ac">
        <el-button @click="handleAllDetailsClick" type="success" size="small" :icon="View" class="mr-10">
          详情
        </el-button>
        <el-button @click="handleAddClick" type="primary" size="small" :icon="Plus">新增</el-button>
        <div class="dots flex flex-c flex-jc flex-ac ml-10">
          <span>.</span>
          <span>.</span>
          <span>.</span>
        </div>
      </div>
    </div>
    <div class="main_box m-10 grid">
      <el-table ref="singleTable" :data="tableData" max-height="340" style="width: 100%" fit :header-cell-style="{
          color: '#000',
          background: '#f2f2f2',
        }">
        <el-table-column prop="identification_number" label="识别号码" align="center">
        </el-table-column>
        <el-table-column prop="box_type" label="箱体类别" align="center">
        </el-table-column>
        <el-table-column prop="license_number" label="显示牌号" align="center">
        </el-table-column>
        <el-table-column prop="other_brands" label="其他牌号" align="center">
        </el-table-column>

        <el-table-column prop="default" label="操作" width="134" fixed="right" align="center">
          <template #default="scope">
            <el-button @click="handleDetailsClick(scope.row)" type="success" size="small">
              详情
            </el-button>
            <el-button @click="handleEditClick(scope.row)" type="primary" size="small">编辑</el-button>
            <!-- <el-popconfirm
              width="220"
              :icon="WarningFilled"
              icon-color="#f56c6c"
              title="是否确认删除"
              confirm-button-type="danger"
              @confirm="handleDelClick(scope.row)"
              placement="top"
              cancel-button-type="primary"
              confirm-button-text="确定"
              cancel-button-text="取消"
            >
              <template #reference>
                <!~~ @click="handleDelClick(scope.row)" ~~>
                <el-button type="danger" size="small">删除</el-button>
              </template>
</el-popconfirm>-->
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 新增   -->
    <el-dialog title="厢牌照添加表" v-model="dialogAddVisible" width="50%" draggable align-center destroy-on-close
      class="dialog_add" :before-close="handleClose">
      <el-form ref="formRef" :model="form" label-width="90px" label-position="top" class="dialog_addform"
        :rules="rules">
        <el-form-item label="识别号码" prop="identificationNumber">
          <el-input v-model="form.identificationNumber" :disabled="form.disabled" maxlength="10" show-word-limit
            placeholder="请输入识别号码" clearable style="width: 100%"></el-input>
        </el-form-item>

        <el-form-item label="箱体类别" prop="boxType">
          <el-select v-model="form.boxType" :disabled="form.disabled" placeholder="请选择箱体类别" size="large"
            style="width: 100%" clearable>
            <el-option v-for="item in boxTypeList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="展示号码" prop="licenseNumber">
          <el-input v-model="form.licenseNumber" :disabled="form.disabled" maxlength="10" show-word-limit
            placeholder="请输入展示号码" clearable style="width: 100%"></el-input>
        </el-form-item>
        <el-form-item label="其他号码" prop="otherBrands">
          <!-- <el-input v-model="form.otherBrands" maxlength="10" show-word-limit placeholder="请输入其他号码" clearable
            style="width: 100%"></el-input> -->
          <el-select v-model="form.otherBrands" :disabled="form.disabled" placeholder="请输入其他号码" size="large"
            style="width: 100%" clearable>
            <el-option v-for="item in otherBrandsList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="箱体容积" prop="volume">
          <el-input v-model="form.volume" :disabled="form.disabled" maxlength="10" show-word-limit placeholder="请输入箱体容积"
            clearable style="width: 100%"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="submitForm" v-if="!form.disabled">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 详情 -->
    <el-dialog title="车辆牌库详情" v-model="dialogVisible" width="70%" draggable align-center destroy-on-close
      :before-close="handleVisibleClose">

      <div class="dialog_header mb-20">
        <el-select class="select mr-10" v-model="selectObj.box_type" placeholder="请选择厢体类别" size="large"
          style="width:180px" clearable>
          <el-option v-for="item in wequipmentListOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-input v-model="selectObj.key" maxlength="20" placeholder="请输入识别号码或归属单位或垃圾来源单位" clearable
          style="width: 340px"></el-input>
        <el-button class="ml-5 mr-5" @click="handleSelectClose" type="primary">搜索</el-button>
        <el-button @click="handleReact" type="primary">重置</el-button>
      </div>
      <el-table ref="singleTable" :data="tableAllData" height="340" max-height="340" style="width: 100%" fit
        :header-cell-style="{
          color: '#000',
          background: '#f2f2f2',
        }">
        <el-table-column prop="identification_number" label="识别号码" align="center">
        </el-table-column>
        <el-table-column prop="box_type" label="箱体类别" align="center">
        </el-table-column>
        <el-table-column prop="license_number" label="显示牌号" align="center">
        </el-table-column>
        <el-table-column prop="other_brands" label="其他牌号" align="center">
        </el-table-column>

        <el-table-column prop="default" label="操作" width="134" fixed="right" align="center">
          <template #default="scope">
            <el-button @click="handleDetailsClick(scope.row)" type="success" size="small">
              详情
            </el-button>
            <el-button @click="handleEditClick(scope.row)" type="primary" size="small">编辑</el-button>

          </template>
        </el-table-column>
      </el-table>
      <div class="pagination_box mt-20">
        <el-pagination small :current-page.sync="currentPage" :page-size.sync="pageSize" :page-sizes="[10, 20, 30, 50]"
          background layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import {
  ref,
  computed,
  watch,
  onMounted,
  onBeforeUnmount,
  reactive,
  shallowRef,
  onUnmounted, getCurrentInstance,
} from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import {
  WarningFilled,
  Plus,
  View,
  Delete,
  Edit,
  Search,
  Share,
  Upload,
} from "@element-plus/icons-vue";
import { getToken } from "@/utils/auth";
// const store = useStore();
const iconPng = new URL("@/assets/img/index/pf.png", import.meta.url).href;

import {
  bucketLicensePlateListApi, bucketAddApi, bucketEditApi,
  getUnitManagement2List, getBoxTypeListApi, licenseAdd,
  licenseEdit,
} from "@/api/resourceManagement";
import { getListBoxNameApi } from "@/api/resourceManagement";
import { useMousePosition } from "@/hooks/dateSelect.ts";
const { timeType } = useMousePosition();
const props: any = defineProps({});
const { proxy } = getCurrentInstance();
const formRef = ref(null);
const rules = {
  identificationNumber: [
    { required: true, message: '请输入识别号码', trigger: 'blur' }
  ],
  boxType: [
    {
      required: true,
      message: "请选择箱体类别",
      trigger: "blur",
    },
  ],
  licenseNumber: [
    {
      required: true,
      message: "请输入展示号码",
      trigger: "blur",
    },
  ],
  otherBrands: [
    {
      required: true,
      message: "请输入其他号码",
      trigger: "blur",
    },
  ],
  volume: [
    {
      required: true,
      message: "请输入桶容积",
      trigger: "blur",
    },
  ],
};
onMounted(() => { });

onBeforeUnmount(() => { });
onUnmounted(() => { });
let dialogVisible = ref(false);
let dialogAddVisible = ref(false);
let form = ref({});
const radiopzq = ref("3");
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);
let tableData = ref([]);
let tableAllData = ref([]);
let otherBrandsList = ref([]);//其他牌号
let boxTypeList = ref([]);//厢体类别
let wequipmentListOptions = ref([]);//厢体类别
let selectObj = ref({
  vehicleType: 99,
  key: null
});


watch(
  timeType,
  () => {
    init();
  },
  {
    immediate: true,
  }
);

function init() {
  getListBoxName();


}
// 厢体库--根据关键字查询搜索，车属单位和车辆类型列表
async function getListBoxName() {
  tableData.value = [];
  let info = {
    pageNo: 1,
    pageSize: 10,
    // licenseType: 1, // 牌照类型 0车牌照 1箱牌照 2全部
    num: 1, // 类型 ：1搜索
    key: null, //搜索值
    box_type: null,
  };
  const res = await getListBoxNameApi(info);
  console.log("厢体库", res, res?.data);
  if (res?.data?.code != 200) return;
  let { result = {} } = res?.data;
  tableData.value = result?.records || [];
  // console.log("厢体库-分页列表查询", tableData.value, result);
}
//桶牌库-分页列表查询  全部
async function getListBoxNameAll() {
  tableAllData.value = [];
  // total.value = 0
  let info = {
    pageNo: currentPage.value,
    pageSize: pageSize.value,
    key: selectObj.value.key || null, //搜索值
    box_type: selectObj.value.box_type || null
  };
  const res = await getListBoxNameApi(info);
  console.log("全部桶牌库", res, res?.data);
  if (res?.data?.code != 200) return;
  let { result = {} } = res?.data;
  tableAllData.value = result?.records || [];
  total.value = Number(result?.total) || 0;
}
// 牌照库-厢体类别查询
async function getManageTableListList() {
  let res = await getBoxTypeListApi({});
  console.log('牌照库-厢体类别查询', res);
  if (res.status != 200) return;
  let { result = [] } = res?.data;
  wequipmentListOptions.value = result.map((item) => {
    return {
      value: item.box_type,
      label: item?.box_type || "null",
    };
  });
  console.log("牌照库-厢体类别查询", result);
}
// 厢体 联想搜索 key: 搜索值   num:搜索类型 1搜索 2 other_brands 其他号码
//   3 box_type 箱体类别  4 管理单位  management_unit
async function compartmentsQuerySearchList(key = null, num = null) {
  let info = {
    pageNo: 1,
    pageSize: 99999,
    num: num, // 类型 ：1搜索
    key: key, //搜索值
    box_type: null,
    unitId: null
  };
  let res = await getListBoxNameApi(info);
  if (res.status != 200) return;
  let { result = {} } = res?.data;
  //console.log("厢体 联想搜索", res.result.records);
  // let List = result?.records.map((item) => {
  //   return {
  //     value: item.id,
  //     label: item?.management_unit || "null",
  //   };
  // });
  let List1 = result?.records.map((item) => {
    return {
      value: item.id,
      label: item?.other_brands || "null",
    };
  });
  let List2 = result?.records.map((item) => {
    return {
      value: item.id,
      label: item?.box_type || "null",
    };
  });
  // this.compartList = this.deWeight(List);//管理公司
  otherBrandsList.value = deWeight(List1);//其他牌号
  boxTypeList.value = deWeight(List2);//厢体类别
  console.log("其他牌号 厢体类别 ", otherBrandsList.value, boxTypeList.value);
  return [...result.records];
}
function deWeight(arr = []) {
  for (var i = 0; i < arr.length - 1; i++) {
    for (var j = i + 1; j < arr.length; j++) {
      if (arr[i].label == arr[j].label) {
        arr.splice(j, 1);
        j--;
      }
    }
  }
  return arr;
}
// 搜索
function handleSelectClose() {
  getListBoxNameAll()
}
// 重置
function handleReact() {
  currentPage.value = 1
  pageSize.value = 10
  selectObj.value = {
    vehicleType: 99,
    key: null
  }
  getListBoxNameAll()
}
// 新增
const handleAddClick = () => {
  console.log(234124, form.value, dialogAddVisible.value);
  dialogAddVisible.value = true;
  compartmentsQuerySearchList()
  form.value = {}
};
// 编辑
const handleEditClick = (scope: Object) => {
  console.log('编辑', scope);

  compartmentsQuerySearchList()
  dialogAddVisible.value = true;
  form.value = {
    identificationNumber: scope.identification_number,
    boxType: scope.box_type,
    licenseNumber: scope.license_number,
    otherBrands: scope.other_brands,
    volume: scope.volume,
    id: scope.id,
    disabled: false
  }
};
// 详情
const handleDetailsClick = (scope: Object) => {
  dialogAddVisible.value = true;
  compartmentsQuerySearchList()

  form.value = {
    identificationNumber: scope.identification_number,
    boxType: scope.box_type,
    licenseNumber: scope.license_number,
    otherBrands: scope.other_brands,
    volume: scope.volume,
    id: scope.id,
    disabled: true
  }
};
// 总的详情
const handleAllDetailsClick = () => {
  dialogVisible.value = true;
  getListBoxNameAll();
  getManageTableListList();// 牌照库-厢体类别查询
};
// 垃圾来源单位
const serviceUnitChange = (e) => {
  console.log('垃圾来源单位', e);
  let service = unitManagement.value.find(item => {
    return item.value == e
  })
  if (service != undefined) form.value.serviceUnit = service.label
}

// 关闭
const handleClose = () => {
  form.value = {};
  dialogAddVisible.value = false;
};
// 关闭
const handleVisibleClose = () => {
  handleReact()
  dialogVisible.value = false;
};
// 删除
const handleDelClick = () => { };
const submitForm = () => {
  console.log(formRef.value, form.value);
  formRef.value.validate(async (valid) => {
    if (valid) {
      delete form.value.disabled
      form.value.licenseType = 1;
      if (form.value?.id) {
        let res = await licenseEdit(form.value);
        if (res?.success || res?.data?.code === 200) {
          ElMessage.success("修改成功!")
          form.value = {};
          formRef.value && formRef.value.resetFields();
          getListBoxName();
          getListBoxNameAll()
          handleClose()
        } else ElMessage.warning(res?.msg||res?.data?.message);
      } else {
        form.value.recordingTime = formatDateDay(new Date())
        let res = await licenseAdd(form.value);
        console.log(12312, res);

        if (res?.success || res?.data?.code === 200) {
          ElMessage.success("添加成功!")
          form.value = {};
          formRef.value && formRef.value.resetFields();
          getListBoxName();
          getListBoxNameAll()
          handleClose()
        } else ElMessage.warning(res?.msg||res?.data?.message);
      }
    } else {
      return false;
    }
  })

};


function formatDateDay(e) {
  e = Number(e)
  /**时间戳转YYYY-MM-DD hh:mm:ss格式
   * @param {时间戳} e
   */
  try {
    e = e.replace(/-/g, "/");
  } catch (err) { }
  var date = new Date(e);
  var YY = date.getFullYear() + "-";
  var MM =
    (date.getMonth() + 1 < 10
      ? "0" + (date.getMonth() + 1)
      : date.getMonth() + 1) + "-";
  var DD = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();

  return YY + MM + DD;
}

// 处理图片预览的功能
const closeImgHandle = () => {
  nextTick(() => {
    let domImageMask = document.querySelector(".el-image-viewer__mask"); // 获取遮罩层dom
    let circleMask = document.querySelector(".el-icon-circle-close"); // 获取遮罩层dom
    circleMask.className = "el-icon-error";
    if (!domImageMask) {
      return;
    }
    domImageMask.addEventListener("click", () => {
      // 点击遮罩层时调用关闭按钮的 click 事件  图片预览
      document.querySelector(".el-image-viewer__close").click();
    });
  });
};

//条数
function handleSizeChange(value) {
  pageSize.value = value; console.log('条数', value);
  getListBoxNameAll()//调取接口
}
function handleCurrentChange(value) {
  //页码发生变化会触发，这个用来触发点击页码时触发的。
  currentPage.value = value; console.log('页码发生变化会触发', value);
  getListBoxNameAll()//调取接口

}
</script>

<style lang="scss" scoped>
.daraBoardStreetAnalysis_content {
  height: 400px;

  .header_box {
    .add_icon {
      margin-right: 5px;
      cursor: pointer;
    }
  }

  .main_box {
    overflow-y: auto;
  }

  .el-radio.el-radio--large {
    height: 30px;
  }

  .el-upload__tip {
    font-size: 13px;
    margin-top: -30px;
    margin-left: 100px;
    color: #939191;
  }
}


.dialog_header::v-deep {
  .select {}

  .el-select {
    height: 32px;
    line-height: 32px;
  }

  .el-input {
    height: 32px;
    line-height: 32px;
  }
}
</style>
<style>
.el-dialog__body {
  padding: 10px 20px 20px;
}
</style>